<?php

namespace App\Http\Controllers\Activity;

use App\Entities\Activity;
use App\Entities\ActivityInfo;
use Illuminate\Container\Container;
use Illuminate\Support\Arr;

class WebApiController
{
    public function copy($id)
    {
        $origin = Activity::query()->findOrFail($id);
        $attributes = $origin->getAttributes();
        Arr::set($attributes, 'name', '[复制]' . Arr::get($attributes, 'name'));
        Arr::set($attributes, 'isPause', Activity::PAUSED);
        Arr::set($attributes, 'publishing_ways', '{}');
        Arr::forget($attributes, ['id', 'created_at', 'updated_at', 'deleted_at']);

        $database = Container::getInstance()->make('db');

        $id = $database->transaction(function () use ($attributes) {
            $copies = new Activity();
            $copies->fill($attributes);
            $copies->save();
            ActivityInfo::sync($copies);

            return $copies->id;
        });

        if (!$id) {
            return response()->failed('复制失败');
        }

        return response()->success(compact('id'));
    }
}
